﻿using System;
using System.Collections.Generic;
using Framework;

namespace Game
{
    public class InitConfigsActionable : IBTreeActionable<StartBTreeContext>
    {
        private static List<Type> _InitConfigTypeList = new List<Type>()
        {
            typeof(SceneConfigEntity),
            typeof(PetConfigEntity),
            typeof(PlayerConfigEntity),
        };

        private int _semaphore;
        
        public void OnStart(StartBTreeContext context)
        {
            _semaphore = _InitConfigTypeList.Count;
            for (int i = 0; i < _InitConfigTypeList.Count; ++i)
            {
                Type configType = _InitConfigTypeList[i];
                ConfigEntity configEntity = (ConfigEntity) Activator.CreateInstance(configType);
                configEntity.AddListener(CommonEntityEvent.OnCompleted, OnConfigCompleted);
                configEntity.Load();
            }
        }

        public void OnEnd(StartBTreeContext context)
        {
        }

        public TaskStatus Update(StartBTreeContext context)
        {
            if (_semaphore <= 0)
            {
                return TaskStatus.Success;  
            }
            return TaskStatus.Running;
        }

        private void OnConfigCompleted(ETEvent emitEvent)
        {
            --_semaphore;
            ConfigEntity configEntity = (ConfigEntity) emitEvent.target;
            configEntity.RemoveListener(CommonEntityEvent.OnCompleted, OnConfigCompleted);
            ConfigSystem.Instance.Add(configEntity);
        }
    }
}